package org.swxjava.assembler.avm1.convert;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.swxjava.assembler.Converter;
import org.swxjava.assembler.MarshallException;
import org.swxjava.assembler.ObjectCompiler;
import org.swxjava.assembler.avm1.AsArray;
import org.swxjava.assembler.avm1.AsArrayElement;
import org.swxjava.util.Log;
import org.swxjava.util.LogFactory;

public class CollectionConverter extends BaseConverter implements Converter {
	
	private static final Log LOG = LogFactory.getLog(CollectionConverter.class);

	public ObjectCompiler convert(Object data) throws MarshallException {
		// First we need to get ourselves the collection data
		Iterator it;
		if (data instanceof Collection) {
			Collection col = (Collection) data;
			it = col.iterator();
		} else if (data instanceof Iterator) {
			it = (Iterator) data;
		} else {
			throw new MarshallException(data.getClass());
		}
		ArrayList<Object> alist = new ArrayList<Object>();
		while(it.hasNext()) {
			alist.add(it.next());
		}
		Object[] objects = alist.toArray();
		// Convert all the data members
		AsArray array = new AsArray();
		for (int i=(objects.length-1); i >= 0; i--) {
			Object member = objects[i];
			ObjectCompiler value;
			try {
				value = config.convert(member);
			} catch (Exception ex) {
				value = config.convert(null);
				LOG.warn("Failed to convert array member " + i + ". Conversion error for type: " + data.getClass().getName(), ex);
			}
			AsArrayElement element = new AsArrayElement(i, value);
			array.add(element);
		}
		return array;
	}
}
